﻿package igz.fleaxy.sound 
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.utils.Timer;
	/**
	 * ...
	 * @author Intelygenz | www.intelygenz.com
	 */
	public class Channel
	{
		
		private var _Timer : Timer;
		private var _Dir : uint;
		private var _SChannel : SoundChannel;
		private var _OnCompleteFunction : Function = null;
		
		private var _VolTo : Number;
		
		public function get $SChannel() : SoundChannel { return _SChannel; }
		
		public var $AutoLoop : Boolean;
		
		public function Channel( p_onCompleteFuncion : Function = null ) {
			_SChannel = new SoundChannel();
			_Timer = new Timer( 50 );
			
			if ( p_onCompleteFuncion != null ) {				
				_OnCompleteFunction = p_onCompleteFuncion;
			}
			
			_Timer.addEventListener( TimerEvent.TIMER, _SetVolumeProg );
			
			
		}
		
		public function $Play( p_sound : Sound) : void {
			var loops : Number =  $AutoLoop ? int.MAX_VALUE : 1;

			_SChannel = p_sound.play(0, loops);
			_SChannel.addEventListener( Event.SOUND_COMPLETE, _onSoundComplete );
		}
		
		public function $VolumeToMax() : void {
			_Dir = 1;
			_VolTo = 1;
			_Timer.start();
		}
		
		public function $VolumeToMin() : void {
			_Dir = 0;
			_VolTo = 0;
			_Timer.start();
		}
		
		public function $VolumeTo( p_vol : Number ) : void {
			
			//dir 0 = bajar volumen
			//dir 1 = subir volumen
			
			_Dir = 0;
			if ( _SChannel.soundTransform.volume >  p_vol ) {
				_Dir = 0;
			} else {
				_Dir  = 1;
			}
			
			_VolTo = p_vol;
			_Timer.start();
		}
		
		private function _SetVolumeProg( e_timerEvent : TimerEvent ) : void {
			var soundT : SoundTransform = _SChannel.soundTransform;
			
			var volume : Number = soundT.volume;
			
			
			//dir 0 = bajar volumen
			//dir 1 = subir volumen
			
			if ( _Dir == 1 ) {
				volume = volume + 0.1;
			} else {
				volume = volume - 0.1;
			}			
			
			
			if ( volume > 1 ) volume = 1;
			if ( volume < 0 ) volume = 0;
			
			soundT = new SoundTransform( volume );
			_SChannel.soundTransform = soundT;
			
			if ( _Dir == 1 ) {
				if ( ( volume >= _VolTo ) || (  volume >= 1 ) ){
					_Timer.stop();
				}
			} else {
				if ( ( volume <= _VolTo ) || ( volume <= 0 ) ){
					_Timer.stop();
					
					//if ( volume <= 0 ) {
						//_SChannel.stop();
					//}
				}
			}	
		
			//if ( ( volume < 0 ) || ( volume > 1 ) ){
				//_Timer.stop();
				//
				//if ( volume <= 0 ) {
					//_SChannel.stop();
				//}
				//
			//}			
		}
		
		public function _onSoundComplete( p_event : Event ) : void {
			if ( _OnCompleteFunction != null ) {
				_OnCompleteFunction();
			}
		}
		
	}

}